# VNC服务器配置和启动脚本
# 为Windows容器配置远程桌面访问

Write-Host "=== 配置VNC远程桌面服务 ===" -ForegroundColor Green

try {
    # 停止可能正在运行的VNC服务
    Write-Host "停止现有VNC服务..." -ForegroundColor Yellow
    Get-Process -Name "tvnserver" -ErrorAction SilentlyContinue | Stop-Process -Force
    Get-Process -Name "winvnc" -ErrorAction SilentlyContinue | Stop-Process -Force

    # 确保TightVNC安装正确
    $vncPath = "C:\Program Files\TightVNC\tvnserver.exe"
    if (!(Test-Path $vncPath)) {
        $vncPath = "C:\Program Files (x86)\TightVNC\tvnserver.exe"
    }
    
    if (!(Test-Path $vncPath)) {
        throw "TightVNC未找到，请确保已正确安装"
    }

    Write-Host "VNC服务器路径: $vncPath" -ForegroundColor Gray

    # 创建VNC配置文件
    $vncConfig = @"
[Params]
Password=8B1B0CFFCF5E7D71
UseVncAuthentication=1
AcceptRfbConnections=1
RfbPort=5900
QueryTimeout=30
QueryAcceptOnTimeout=0
LocalInputPriorityTimeout=3
LocalInputPriority=0
BlockRemoteInput=0
BlockLocalInput=0
IpAccessControl=
ConnectPriority=0
DisconnectAction=0
AcceptCutText=1
SendCutText=1
DisableWallpaper=1
RemoveWallpaper=1
"@

    # 写入配置文件
    $configPath = "C:\Program Files\TightVNC\tvnserver.ini"
    $vncConfig | Out-File -FilePath $configPath -Encoding ASCII -Force
    Write-Host "VNC配置文件已创建: $configPath" -ForegroundColor Gray

    # 设置注册表配置
    Write-Host "配置VNC注册表设置..." -ForegroundColor Yellow
    
    $regPath = "HKLM:\SOFTWARE\TightVNC\Server"
    if (!(Test-Path $regPath)) {
        New-Item -Path $regPath -Force | Out-Null
    }

    # VNC密码: vnc123 (8B1B0CFFCF5E7D71 是 vnc123 的加密值)
    Set-ItemProperty -Path $regPath -Name "Password" -Value ([byte[]](0x8B,0x1B,0x0C,0xFF,0xCF,0x5E,0x7D,0x71)) -Type Binary -Force
    Set-ItemProperty -Path $regPath -Name "UseVncAuthentication" -Value 1 -Type DWord -Force
    Set-ItemProperty -Path $regPath -Name "AcceptRfbConnections" -Value 1 -Type DWord -Force
    Set-ItemProperty -Path $regPath -Name "RfbPort" -Value 5900 -Type DWord -Force
    Set-ItemProperty -Path $regPath -Name "RemoveWallpaper" -Value 1 -Type DWord -Force
    Set-ItemProperty -Path $regPath -Name "DisableWallpaper" -Value 1 -Type DWord -Force

    # 启动VNC服务器
    Write-Host "启动VNC服务器..." -ForegroundColor Yellow
    
    # 使用应用模式启动VNC（不作为Windows服务）
    $vncArgs = @(
        "-run"
        "-shareall"
        "-rfbport", "5900"
        "-controlapp"
    )

    Start-Process -FilePath $vncPath -ArgumentList $vncArgs -WindowStyle Hidden
    Start-Sleep -Seconds 3

    # 验证VNC服务器是否启动
    $vncProcess = Get-Process -Name "tvnserver" -ErrorAction SilentlyContinue
    if ($vncProcess) {
        Write-Host "✅ VNC服务器启动成功 (PID: $($vncProcess.Id))" -ForegroundColor Green
        Write-Host "VNC端口: 5900" -ForegroundColor Gray
        Write-Host "VNC密码: vnc123" -ForegroundColor Gray
    } else {
        throw "VNC服务器启动失败"
    }

    # 配置Windows防火墙
    Write-Host "配置防火墙规则..." -ForegroundColor Yellow
    try {
        New-NetFirewallRule -DisplayName "VNC Server" -Direction Inbound -Protocol TCP -LocalPort 5900 -Action Allow -ErrorAction SilentlyContinue
        Write-Host "防火墙规则已配置" -ForegroundColor Gray
    } catch {
        Write-Warning "防火墙配置失败: $($_.Exception.Message)"
    }

    # 显示连接信息
    Write-Host "`n=== VNC连接信息 ===" -ForegroundColor Cyan
    Write-Host "VNC地址: <宿主机IP>:5900" -ForegroundColor White
    Write-Host "VNC密码: vnc123" -ForegroundColor White
    Write-Host "用户账户: vncuser / vnc123" -ForegroundColor White
    
    # 获取容器IP（如果可能）
    try {
        $containerIP = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.IPAddress -ne "127.0.0.1"} | Select-Object -First 1).IPAddress
        if ($containerIP) {
            Write-Host "容器IP: $containerIP:5900" -ForegroundColor White
        }
    } catch {
        Write-Host "无法获取容器IP地址" -ForegroundColor Yellow
    }

    Write-Host "`n推荐VNC客户端:" -ForegroundColor Gray
    Write-Host "- Windows: TightVNC Viewer, RealVNC Viewer" -ForegroundColor Gray
    Write-Host "- macOS: Screen Sharing, VNC Viewer" -ForegroundColor Gray
    Write-Host "- 跨平台: RealVNC Viewer" -ForegroundColor Gray

    return $true

} catch {
    Write-Error "VNC配置失败: $($_.Exception.Message)"
    Write-Host "错误详情: $($_.Exception)" -ForegroundColor Red
    return $false
} 